package edu.iss.demo.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.iss.demo.exception.LeaveDetailNotFound;
import edu.iss.demo.exception.LeaveTypeNotFound;
import edu.iss.demo.model.LeaveDetail;
import edu.iss.demo.model.LeaveType;
import edu.iss.demo.repository.LeaveDetailsRepository;
import edu.iss.demo.repository.LeaveTypeRepository;

@Service
public class LeaveTypeServiceImpl implements LeaveTypeService {

	@Resource
	LeaveTypeRepository leaveTypeRepository;

	@Override
	@Transactional
	public LeaveType create(LeaveType s) {
		LeaveType e = s;
		return leaveTypeRepository.save(e);
	}

	@Override
	@Transactional(rollbackFor = LeaveTypeNotFound.class)
	public LeaveType delete(long id) throws LeaveTypeNotFound{
		LeaveType deletedLeaveType= leaveTypeRepository.findOne(id);

		if (deletedLeaveType== null)
			throw new LeaveTypeNotFound();

		leaveTypeRepository.delete(deletedLeaveType);
		return deletedLeaveType;
	}

	@Override
	@Transactional
	public List<LeaveType> findAll() {
		
		return leaveTypeRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor = LeaveTypeNotFound.class)
	public LeaveType update(LeaveType s) throws LeaveTypeNotFound{
		LeaveType updatedLeaveType = leaveTypeRepository.findOne(s.getLeaveTypeId());

		if (updatedLeaveType == null)
			throw new LeaveTypeNotFound();

		updatedLeaveType.setName(s.getName());
		updatedLeaveType.setAllowedDays(s.getAllowedDays());
		
		leaveTypeRepository.flush();
		return updatedLeaveType;
	}

	@Override
	@Transactional
	public LeaveType findById(long id) {
		return leaveTypeRepository.findOne(id);
	}

}
